package com.aps.apspda.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatDialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.activity.StartFunctionActivity;
import com.aps.apspda.activity.StartFunction_SingulationActivity;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.callback.StringCommonCallBack;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.EqpEntity;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.Map;


/**
 * @author huangxin
 * @date 2015/11/10
 * @desc 通用dialog
 */
public class GeneralFragmentDialog extends AppCompatDialogFragment {
    private String tips, leftStr, rightStr;
    private View.OnClickListener onClickListener;
    private StringCommonCallBack callBack;
    private int where = 1;
    private EditText etRemark;

    @Override
    public void show(FragmentManager manager, String tag) {
        if (!isAdded()) {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag);
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (dialog != null) {
            dialog.getWindow().setLayout((int) (StaticMembers.SCREEN_WIDTH * 0.8), ViewGroup.LayoutParams.WRAP_CONTENT);
        }
    }

    public void setCallBackAndWhere(StringCommonCallBack callBack, int where) {
        this.callBack = callBack;
        this.where = where;
    }

    public void setData(String tips, View.OnClickListener confirmListener) {
        this.tips = tips;
        this.onClickListener = confirmListener;
    }

    public void setData(String tips, String leftStr, String rightStr, View.OnClickListener confirmListener) {
        this.tips = tips;
        this.onClickListener = confirmListener;
        this.leftStr = leftStr;
        this.rightStr = rightStr;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_genaral, null);
        getDialog().getWindow().setGravity(Gravity.CENTER); // 非常重要：设置对话框弹出的位置
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().setWindowAnimations(R.style.BottomDialog); // 添加动画
        getDialog().setCancelable(false);
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN && (keyCode == 138 || keyCode == 240 || keyCode == 241 || keyCode == 242)) {
                    etRemark.requestFocus();
                    etRemark.setText("");
                }
                return false;
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        Button btnConfirm = view.findViewById(R.id.btnConfirm);//确认按钮
        Button btnCancel = view.findViewById(R.id.btnCancel);//取消按钮
        etRemark = view.findViewById(R.id.etRemark);//dialog内容
        if (leftStr != null && leftStr.length() > 0) {
            btnCancel.setText(leftStr);
        }
        if (rightStr != null && rightStr.length() > 0) {
            btnConfirm.setText(rightStr);
        }
        etRemark.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        etRemark.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, final int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        String[] eqpList = StaticMembers.CUR_USER.getEQPLIST().split(";");
                        boolean isHave = false;
                        for (String str : eqpList) {
                            if (str.equals(s.toString().trim())) {
                                isHave = true;
                                break;
                            }
                        }
                        if (!isHave) {
                            ToastUtils.showFreeToast("设备不存在或没有权限", getActivity(), false, Toast.LENGTH_SHORT);
                        } else {
                            StaticMembers.LOG_EQP_ID = s.toString().trim();
                            if (where == 1 && !StaticMembers.LOG_EQP_ID.toLowerCase().contains("fb")
                                    && !StaticMembers.LOG_EQP_ID.toLowerCase().contains("fd")) {
                                doJump();
                            } else {
                                callBack.onCallback(StaticMembers.LOG_EQP_ID);
                            }
                        }
                    } else {
                        ToastUtils.showFreeToast("扫描信息有误", getActivity(), false, Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            getActivity(), false, Toast.LENGTH_SHORT);
                    return;
                }
                if (etRemark.getText().toString().trim().length() == 0) {
                    ToastUtils.showFreeToast("请扫描设备", getActivity(), false, Toast.LENGTH_SHORT);
                } else {
                    String[] eqpList = StaticMembers.CUR_USER.getEQPLIST().split(";");
                    boolean isHave = false;
                    for (String str : eqpList) {
                        if (str.equals(etRemark.getText().toString().trim())) {
                            isHave = true;
                            break;
                        }
                    }
                    if (!isHave) {
                        ToastUtils.showFreeToast("设备不存在或没有权限", getActivity(), false, Toast.LENGTH_SHORT);
                    } else {
                        StaticMembers.LOG_EQP_ID = etRemark.getText().toString().trim();
                        if (where == 1 && !StaticMembers.LOG_EQP_ID.toLowerCase().contains("fb")
                                && !StaticMembers.LOG_EQP_ID.toLowerCase().contains("fd")) {
                            doJump();
                        } else {
                            callBack.onCallback(StaticMembers.LOG_EQP_ID);
                        }
                    }
                }
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    private void doJump() {
        EntityCallBack<BaseEntity<EqpEntity>> callBack = new DialogEntityCallBack<BaseEntity<EqpEntity>>
                (new TypeToken<BaseEntity<EqpEntity>>() {
                }.getType(), getFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<EqpEntity>> response) {
                if (response.body().isSuccess(getActivity())) {
                    EqpEntity eqpEntity = response.body().getData();
                    Intent intent = new Intent();
                    if (eqpEntity.getEQPTYPE().equals("Singulation-DISCO")) {
                        intent.setClass(getActivity(), StartFunction_SingulationActivity.class);
                    } else {
                        intent.setClass(getActivity(), StartFunctionActivity.class);
                    }
                    intent.putExtra("eqpID", StaticMembers.LOG_EQP_ID);
                    startActivity(intent);
                    dismiss();
                } else {
                    AppUtils.loadFail(response.body().getMessage(),getActivity().getSupportFragmentManager(),getContext());//modify by bunny
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<EqpEntity>> response) {
                super.onError(response);
                AppUtils.saveErrorMessages(response.getException(), "ShowEqpType");
                ToastUtils.showFreeToast("连接服务器失败",
                        getActivity(), false, Toast.LENGTH_SHORT);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", StaticMembers.LOG_EQP_ID);
      //  NetUtils.requestNet(this, "/ShowEQPInfoC2E", map, callBack);
        NetUtils.requestNet(this, "/ShowEqpType", map, callBack);
    }
}
